package com.chenfan.filestore.utils;

import com.chenfan.ccp.common.exception.ApiException;
import com.chenfan.filestore.exception.FileStoreCode;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Freemarker 解析器 (https://freemarker.apache.org/)
 */
@Component
@AllArgsConstructor
@Slf4j
public class FreemarkerUtil {

    public static String resolve(String templateContent, Object paramMap) {
        String result = "";
        //自定义函数
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("11", templateContent);
        cfg.setTemplateLoader(stringLoader);
        cfg.setNumberFormat("#");
        try {
            Template template = cfg.getTemplate("11", "UTF-8");
            StringWriter writer = new StringWriter();
            template.process(paramMap, writer);
            result = writer.toString();

        } catch (Exception e) {
            log.error("模板解析失败",e);
            e.printStackTrace();
            throw new ApiException(FileStoreCode.TEMPLATE_EXPAIN_FAILED);
        }
        return result;
    }
    @Data
    static class Parm {
        private String supplierCodes;
        private String startDate;
        private String sort;
        private String sortField;
    }
    public static void main(String[] args){
        test4();
    }

    public static void test2() {
        String aa = "Valacy's 梵老师".replaceAll("\\'", "\\\\'");
        System.out.println(aa);
    }


    public static void test3() {
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> request = new HashMap<>();
        request.put("sort","Valacy's 梵老师");
        request.put("orderTypes", Arrays.asList(1,2,7));

        paramMap.put("request", request);
        String templateContent = "${request.sort?replace('\\'','%','ri')}";
        System.out.println(resolve(templateContent, paramMap));
    }

    public static void test4() {

        Map<String, Object> paramMap = new HashMap<>();
        Map<String, Object> request = new HashMap<>();
        request.put("sort",null);
        int[] array = {1, 2, 3, 4, 5,6,7};
        request.put("orderTypes", array);
        String templateContent = "<#if orderTypes?? && (orderTypes?seq_contains(7))> 0)> qqqqq</#if>";
        System.out.println(resolve(templateContent, paramMap));
    }

    public static void test1() {
        Map<String, Object> paramMap = new HashMap<>();
//        Map<String, Object> request = new HashMap<>();
//        request.put("supplierCodes","supplierCodes1111,supplierCodes2111");
//        request.put("startDate","startDate22222");
//        request.put("sort","sort3333");
//        request.put("sortField","sortField4444");
        Parm request = new Parm();
        request.setSort("sort3333");
        request.setStartDate("startDate22222");
        request.setSupplierCodes("startDate22222");
        request.setSortField("sortField4444");

        paramMap.put("request",request);
        String templateContent= "select\n" +
                "    supplier_uni_code,\n" +
                "    supplier_abbr_name,\n" +
                "    supplier_type,\n" +
                "    supply_product_category,\n" +
                "    supplier_core_product,\n" +
                "    po_qty,\n" +
                "    spu_cnt,\n" +
                "    po_amt,\n" +
                "    qualified_arrival_qty,\n" +
                "    qualified_arrival_amt,\n" +
                "    owe_qty,\n" +
                "    owe_amt,\n" +
                "    arrival_qty,\n" +
                "    qualified_qty,\n" +
                "    delay_over_2d_arrival_qty,\n" +
                "    qa_reject_qty,\n" +
                "    return_qty,\n" +
                "    arrival_ratio,\n" +
                "    reject_ratio,\n" +
                "    return_ratio,\n" +
                "    delay_ratio,\n" +
                "    owe_ratio,\n" +
                "    brand_id,\n" +
                "    brand_name,\n" +
                "    case when reject_ratio <= 0.03 then 100\n" +
                "    when reject_ratio <=0.05 then 90\n" +
                "    when reject_ratio<=0.07 then 80\n" +
                "    when reject_ratio<=0.08 then 70\n" +
                "    when reject_ratio<=0.09 then 60\n" +
                "    else 0 end as reject_score,\n" +
                "    case when return_ratio<=0.002 then 100\n" +
                "    when return_ratio <=0.004 then 90\n" +
                "    when return_ratio <=0.006 then 80\n" +
                "    when return_ratio <=0.01 then 70\n" +
                "    else 0 end as return_score,\n" +
                "    case when delay_ratio<=0.1 then 100\n" +
                "    when delay_ratio <=0.15 then 90\n" +
                "    when delay_ratio <=0.2 then 80\n" +
                "    when delay_ratio <=0.25 then 70\n" +
                "    when delay_ratio <=0.3 then 60\n" +
                "    else 0 end as delay_score,\n" +
                "    cast(0 as int) as fuliao_flag,\n" +
                "    class_code_num,\n" +
                "    (0.4 * reject_score) + (0.2 * return_score) + (0.4 * delay_score) as overall_score,\n" +
                "    case when overall_score <60 then 'D'\n" +
                "    when overall_score =60 then 'C'\n" +
                "    when overall_score <=80 then 'C'\n" +
                "    when overall_score <=90 then 'B'\n" +
                "    else 'A' end as overall_level\n" +
                "from (\n" +
                "    select\n" +
                "        supplier_uni_code,\n" +
                "        supplier_abbr_name,\n" +
                "        supplier_type,\n" +
                "        supply_product_category,\n" +
                "        supplier_core_product,\n" +
                "        IFNULL(SUM(po_qty),0) as po_qty,\n" +
                "        IFNULL(SUM(spu_cnt),0) as spu_cnt,\n" +
                "        SUM(po_amt) as po_amt,\n" +
                "        IFNULL(SUM(qualified_arrival_qty),0) as qualified_arrival_qty,\n" +
                "        SUM(qualified_arrival_amt) as qualified_arrival_amt,\n" +
                "        IFNULL(SUM(owe_qty),0) as owe_qty,\n" +
                "        SUM(owe_amt) as owe_amt,\n" +
                "        IFNULL(SUM(arrival_qty),0) as arrival_qty,\n" +
                "        IFNULL(SUM(qualified_qty),0) as qualified_qty,\n" +
                "        IFNULL(SUM(delay_over_2d_arrival_qty),0) as delay_over_2d_arrival_qty,\n" +
                "        IFNULL(SUM(qa_reject_qty),0) as qa_reject_qty,\n" +
                "        IFNULL(SUM(return_qty),0) return_qty,\n" +
                "        IF(po_qty == 0, 0,round(qualified_arrival_qty/po_qty,4)) as arrival_ratio,  /*到货率*/\n" +
                "        IF(arrival_qty == 0, 0, round(qa_reject_qty/arrival_qty,4)) as reject_ratio, /*售前退次率*/\n" +
                "        IF(qualified_qty == 0, 0, round(return_qty/qualified_qty,4)) as return_ratio, /*售后退次率*/\n" +
                "        IF(qualified_qty == 0, 0, round(delay_over_2d_arrival_qty/qualified_qty,4)) as delay_ratio, /*延期率*/\n" +
                "        IF(po_qty == 0, 0, round(owe_qty/po_qty,4)) as owe_ratio,/*欠货率*/\n" +
                "        sum(class_code_num) as class_code_num,\n" +
                "        brand_id,\n" +
                "        brand_name\n" +
                "    from (\n" +
                "            select\n" +
                "                dss.supplier_uni_code as supplier_uni_code,\n" +
                "                dss.supplier_abbr_name as supplier_abbr_name,\n" +
                "                dss.supplier_type as supplier_type,\n" +
                "                dss.supply_product_category as supply_product_category,\n" +
                "                dss.supplier_core_product as supplier_core_product,\n" +
                "                dss.month_id as month_id,\n" +
                "                dss.po_qty as po_qty,\n" +
                "                dss.spu_cnt as spu_cnt,\n" +
                "                dss.po_amt as po_amt,\n" +
                "                dss.qualified_arrival_qty as qualified_arrival_qty,\n" +
                "                dss.qualified_arrival_amt as qualified_arrival_amt,\n" +
                "                dss.owe_qty as owe_qty,\n" +
                "                dss.owe_amt as owe_amt,\n" +
                "                dss.arrival_qty as arrival_qty,\n" +
                "                dss.qualified_qty as qualified_qty,\n" +
                "                dss.delay_over_2d_arrival_qty as delay_over_2d_arrival_qty,\n" +
                "                dss.qa_reject_qty as qa_reject_qty,\n" +
                "                dss.return_qty as return_qty,\n" +
                "                tmp.class_code_num as class_code_num,\n" +
                "                brand.brand_id as brand_id,\n" +
                "                brand.brand_name as brand_name\n" +
                "            from (\n" +
                "            select * from supplier_chain.dws_scm_score_supplier_shop\n" +
                "            <#if request.supplierCodes?? && request.supplierCodes !=''>\n" +
                "            where supplier_uni_code in (\n" +
                "            <#list request.supplierCodes?split(\",\") as x>\n" +
                "                '${x}'\n" +
                "                <#if x_has_next>\n" +
                "                ,\n" +
                "                </#if>\n" +
                "                </#list>\n" +
                "                )\n" +
                "            </#if>\n" +
                "        ) dss\n" +
                "        left join (\n" +
                "        select tmp1.supplier_uni_code, tmp1.mouth_id, sum(tmp1.total_class_code) as class_code_num\n" +
                "        from(\n" +
                "            select dsv.supplier_uni_code,dsv.product_code,toYYYYMM(dsv.contract_end_date) as mouth_id,COUNT(DISTINCT dp.p_class_code) total_class_code\n" +
                "            from supplier_chain.dws_scm_view_by_po dsv\n" +
                "            left join dim.d_product dp on dsv.product_code = dp.product_code\n" +
                "            group by dsv.supplier_uni_code,dsv.product_code,toYYYYMM(dsv.contract_end_date),dp.p_class_code\n" +
                "        ) tmp1 group by tmp1.supplier_uni_code,tmp1.mouth_id\n" +
                "    ) tmp on tmp.supplier_uni_code= dss.supplier_uni_code and dss.month_id = toInt32(tmp.mouth_id)\n" +
                "    left join (select * from dim.d_scm_brand_mapping_shop where scm_flag=1) mapping on dss.shop_id = mapping.shop_id \n" +
                "    left join dim.d_scm_brand brand on brand.brand_id = mapping.scm_brand_id    \n" +
                "    where 1=1\n" +
                "    <#if request.startDate?? && request.startDate !=''>\n" +
                "        and dss.month_id >= toInt32(toYYYYMM(toDate('${request.startDate}')))\n" +
                "    </#if>\n" +
                "    <#if request.endDate?? && request.endDate !=''>\n" +
                "        and dss.month_id <= toInt32(toYYYYMM(toDate('${request.endDate}')))\n" +
                "    </#if>\n" +
                "    )\n" +
                "    group by supplier_uni_code,\n" +
                "    supplier_abbr_name,\n" +
                "    supplier_type,\n" +
                "    supply_product_category,\n" +
                "    supplier_core_product,\n" +
                "    brand_id,\n" +
                "    brand_name  \n" +
                ")\n" +
                "<#if request.sort?? && request.sort!='' && request.sortFiled?? && request.sortFiled != ''>\n" +
                "    order by ${request.sortFiled} ${request.sort}\n" +
                "<#else>\n" +
                "    order by supplier_uni_code,brand_id\n" +
                "</#if>";
        System.out.println(resolve(templateContent, paramMap));
    }


}
